package com.jaya.budan.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.StrictMode;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.google.gson.Gson;
import com.jaya.budan.R;
import com.jaya.budan.adapter.Photo_Album_Adapter;
import com.jaya.budan.base.BaseActivity;
import com.jaya.budan.bean.COS_GetToken;
import com.jaya.budan.connect.RequestConnect;
import com.jaya.budan.utils.ImageUtils;
import com.jaya.budan.utils.MyCredentialProvider;
import com.jaya.budan.utils.ToolUtils;
import com.jaya.budan.utils.VolleyUtil;
import com.jaya.budan.views.CommonPopWindow;
import com.jaya.budan.views.MyGridView;
import com.jaya.budan.views.MyListView;
import com.tencent.cos.xml.CosXmlService;
import com.tencent.cos.xml.CosXmlServiceConfig;
import com.tencent.cos.xml.exception.CosXmlClientException;
import com.tencent.cos.xml.exception.CosXmlServiceException;
import com.tencent.cos.xml.listener.CosXmlProgressListener;
import com.tencent.cos.xml.listener.CosXmlResultListener;
import com.tencent.cos.xml.model.CosXmlRequest;
import com.tencent.cos.xml.model.CosXmlResult;
import com.tencent.cos.xml.model.object.PutObjectRequest;
import com.tencent.cos.xml.transfer.COSXMLUploadTask;
import com.tencent.cos.xml.transfer.TransferConfig;
import com.tencent.cos.xml.transfer.TransferManager;
import com.tencent.cos.xml.transfer.TransferState;
import com.tencent.qcloud.core.auth.QCloudCredentialProvider;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class PhotoAlbum_Activity extends BaseActivity implements View.OnClickListener, CommonPopWindow.ViewClickListener {

    private List<String> photo_data;
    private MyGridView gv_photo_album;
    private RelativeLayout back;
    private ImageView iv_photo_album;
    private TextView tv_album_all;
    private static final int TAKE_PHOTO = 0;
    private static final int PICK_PHOTO = 1;
    private static final int RESULT_REQUEST_CODE = 2;
    private Uri photoUri;
    /**
     * CosXmlService 是您访问 COS 服务的核心类，它封装了所有 COS 服务的基础 API 方法。
     *
     * 每一个CosXmlService 对象只能对应一个 region，如果您需要同时操作多个 region 的
     * Bucket，请初始化多个 CosXmlService 对象。
     */
    private CosXmlService cosXmlService;
    /**
     *TransferManager进一步封装了CosXmlService的上传和下载接口，当您需要
     * 上传文件到 COS 或者从 COS 下载文件时，请优先使用这个类。
     */
    private COSXMLUploadTask cosxmlTask;
    private String access_token, currentUploadPath, bucket;
    private int cos_type;

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_photo_album);
        Intent intent = getIntent();
        access_token = intent.getStringExtra("access_token");
        bucket = intent.getStringExtra("bucket");
        cos_type = intent.getIntExtra("cos_type", 2);
        back = findViewById(R.id.back);
        gv_photo_album = findViewById(R.id.gv_photo_album);
        iv_photo_album = findViewById(R.id.iv_photo_album);
        tv_album_all = findViewById(R.id.tv_album_all);
        back.setOnClickListener(this);
        iv_photo_album.setOnClickListener(this);
        tv_album_all.setOnClickListener(this);
        photo_data = ImageUtils.getSystemPhotoList(this);
        gv_photo_album.setHorizontalSpacing(15);
        gv_photo_album.setVerticalSpacing(15);
        if (photo_data.size() > 0){
            gv_photo_album.setAdapter(new Photo_Album_Adapter(this, photo_data, null, null, 0));
        }
        gv_photo_album.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String path = photo_data.get(position);
                Log.d("fill", path);
                if (ToolUtils.isEmpty(path)){ //空值

                } else {
//                    Intent intent1 = new Intent(PhotoAlbum_Activity.this, Crop_Picture_Activity.class);
//                    intent1.putExtra("path", path);
//                    startActivity(intent1);
                    try {
                        File file = new File(path);
                        cropPhoto(Uri.fromFile(file));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    currentUploadPath = path;
                }
            }
        });
        // android 7.0系统解决拍照的问题
        StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectAll().penaltyLog().build());
        StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectAll().penaltyLog().build());
        cosxmlTask = null;
    }

    /**
     * 自定义图片名，获取照片的file
     */
    private File createImgFile() throws IOException {
        //创建文件
        String fileName = "img_" + new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()) + ".jpg";//确定文件名
        File dir;
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
//            dir = Environment.getExternalStorageDirectory();
            dir = getExternalCacheDir();
//            dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
        } else {
            dir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        }
        File tempFile = new File(dir.getPath(), fileName);
        if (tempFile.exists()) {
            tempFile.delete();
        }
        tempFile.createNewFile();
        //获取文件路径
        currentUploadPath = tempFile.getAbsolutePath();
        return tempFile;
    }

    /**
     * 调用系统的裁剪
     * @param uri
     */
    public void cropPhoto(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
//        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
//        intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        intent.putExtra("crop", "true");
//        intent.putExtra("scale", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 150);
        intent.putExtra("outputY", 150);
        intent.putExtra("return-data", true);
//        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        startActivityForResult(intent, RESULT_REQUEST_CODE);
    }

    //将图片添加进手机相册
    private void galleryAddPic() {
        Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        mediaScanIntent.setData(photoUri);
        this.sendBroadcast(mediaScanIntent);
//        try {
//            Bitmap head = BitmapFactory.decodeStream(getContentResolver().openInputStream(photoUri));
//            iv_fill_information_icon.setImageBitmap(head);
//            ImageUtils.saveBitmapToFile(head, createImgFile().getAbsolutePath());
//            upload();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
    }

    //上传图片
    public void upload(String currentUploadPath, String bucket, String access_token, Context context, int type){
        cosxmlTask = null;
        JSONObject object = new JSONObject();
        try {
            object.put("bucket", bucket);//存储桶  头像=head  certify=实名认证
        } catch (JSONException e) {
            e.printStackTrace();
        }
        postCOS_token_Data(object, currentUploadPath, access_token, context, bucket, type);//获取COS存储token
    }

    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.back:
                finish();
                break;
            case R.id.iv_photo_album:
                if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                    //只是加了一个uri作为地址传入
                    Intent intent2 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    try {
                        File photoFile = createImgFile();
                        photoUri = Uri.fromFile(photoFile);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    cropPhoto(photoUri);
                    intent2.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);//指定了存储的路径的uri，那么返回的data就为null
                    startActivityForResult(intent2, TAKE_PHOTO);
                } else {
                    ToolUtils.showToast(this, "SD卡不可用~");
                }
                break;
            case R.id.tv_album_all:
                if (ContextCompat.checkSelfPermission(PhotoAlbum_Activity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(PhotoAlbum_Activity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
                } else {
                    openAlbum();
                }
                break;
            default:
                break;
        }
    }

    private void openAlbum() {
        Intent intent = new Intent("android.intent.action.GET_CONTENT");
        intent.setType("image/*");
        startActivityForResult(intent, PICK_PHOTO);
    }

    @SuppressLint("NonConstantResourceId")
    @Override
    public void getChildView(final PopupWindow mPopupWindow, View view, int mLayoutResId) {
        switch (mLayoutResId) {
            case R.layout.pop_photo_album:
                MyListView lv_photo_album = view.findViewById(R.id.lv_photo_album);
//                Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
//                startActivityForResult(intent, 1);
                lv_photo_album.setAdapter(new Photo_Album_Adapter(PhotoAlbum_Activity.this, null, null, null, 4));
                lv_photo_album.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                    }
                });
                break;
            default:
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && data != null) {
            switch (requestCode) {
                case TAKE_PHOTO:
                    galleryAddPic();
                    break;
                case PICK_PHOTO:
                    if (Build.VERSION.SDK_INT>=19)
                        handImage(data);
                    else handImageLow(data);
                    break;
                case RESULT_REQUEST_CODE:
                    Log.d("fill", "111" + currentUploadPath);
                    Bundle extras = data.getExtras();
                    if (extras != null) {
                        Bitmap head = extras.getParcelable("data");
//                        Bitmap bitmap = BitmapFactory.decodeFile(currentUploadPath);
//                        iv_fill_information_icon.setImageBitmap(bitmap);
                        if (head != null) {
//                                iv_fill_information_icon.setImageBitmap(head);//按钮加载图片
                            ImageUtils.bitmapToBase64(head);//base64加密
                            try {
                                ImageUtils.saveBitmapToFile(head, currentUploadPath);
                                PhotoAlbum_Activity.this.runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        upload(currentUploadPath, bucket, access_token, PhotoAlbum_Activity.this, cos_type);
                                    }
                                });
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }
                    break;
                default:
                    break;
            }
        }
    }

    //安卓版本大于4.4的处理方法
    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    private void handImage(Intent data){
        String path =null;
        Uri uri = data.getData();
        //根据不同的uri进行不同的解析
        if (DocumentsContract.isDocumentUri(this,uri)){
            String docId = DocumentsContract.getDocumentId(uri);
            if ("com.android.providers.media.documents".equals(uri.getAuthority())){
                String id = docId.split(":")[1];
                String selection = MediaStore.Images.Media._ID+"="+id;
                path = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,selection);
            }else if("com.android.providers.downloads.documents".equals(uri.getAuthority())){
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"),Long.valueOf(docId));
                path = getImagePath(contentUri,null);
            }
        }else if ("content".equalsIgnoreCase(uri.getScheme())){
            path = getImagePath(uri,null);
        }else if ("file".equalsIgnoreCase(uri.getScheme())){
            path = uri.getPath();
        }
        //展示图片
        displayImage(path);
    }

    //安卓小于4.4的处理方法
    private void handImageLow(Intent data){
        Uri uri = data.getData();
        String path = getImagePath(uri,null);
        displayImage(path);
    }

    //根据路径展示图片的方法
    private void displayImage(String imagePath){
        if (imagePath != null){
            Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
//            upload();
        } else {
            ToolUtils.showToast(this, "图片设置失败");
        }
    }

    //content类型的uri获取图片路径的方法
    private String getImagePath(Uri uri,String selection) {
        String path = null;
        Cursor cursor = getContentResolver().query(uri,null,selection,null,null);
        if (cursor!=null){
            if (cursor.moveToFirst()){
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }
            cursor.close();
        }
        return path;
    }

    /**
     * 网络请求
     * @param object
     */
    private void postCOS_token_Data(JSONObject object, String cos_path, String access_token, Context context, String cos_bucket, int type) {
        JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, RequestConnect.get_COS_sessionToken_Url + access_token, object, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {
                Log.d("fill_information", jsonObject.toString());
                try {
                    int code = jsonObject.optInt("code");
                    int status = jsonObject.optInt("status");
                    String message = jsonObject.getString("message");
                    if (code == 0) {
                        Gson gson = new Gson();
                        JSONObject info = jsonObject.getJSONObject("info");
                        COS_GetToken getToken = gson.fromJson(info.toString(), COS_GetToken.class);
                        SharedPreferences preferences = context.getSharedPreferences("user_limit", Context.MODE_PRIVATE);
                        // 创建 CosXmlServiceConfig 对象，根据需要修改默认的配置参数
                        CosXmlServiceConfig serviceConfig = new CosXmlServiceConfig.Builder()
                                .setRegion("ap-beijing")
                                .isHttps(true) // 使用 HTTPS 请求, 默认为 HTTP 请求
                                .builder();
                        //初始化 {@link QCloudCredentialProvider} 对象，来给 SDK 提供临时密钥
                        QCloudCredentialProvider credentialProvider = new MyCredentialProvider(getToken);
                        cosXmlService = new CosXmlService(context, serviceConfig, credentialProvider);
                        TransferConfig transferConfig = new TransferConfig.Builder().build();
                        /*若有特殊要求，则可以如下进行初始化定制。例如限定当对象 >= 2M 时，启用分块上传，且分块上传的分块大小为1M，当源对象大于5M时启用分块复制，且分块复制的大小为5M。*/
//                        TransferConfig transferConfig = new TransferConfig.Builder()
//                                .setDividsionForCopy(5 * 1024 * 1024) // 是否启用分块复制的最小对象大小
//                                .setSliceSizeForCopy(5 * 1024 * 1024) // 分块复制时的分块大小
//                                .setDivisionForUpload(2 * 1024 * 1024) // 是否启用分块上传的最小对象大小
//                                .setSliceSizeForUpload(1024 * 1024) // 分块上传时的分块大小
//                                .build();
                        TransferManager transferManager = new TransferManager(cosXmlService, transferConfig);
                        if (ToolUtils.isEmpty(cos_path)) {
                            ToolUtils.showToast(context, "请先选择文件");
                            return;
                        }
                        if (cosxmlTask == null) {

                        } else {
                            ToolUtils.showToast(context, "当前文件未处理完毕，不能选择新文件");
                            cosxmlTask = null;
                        }
                        //为了示例简单明了 正在处理文件时不允许选择文件
//            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);//选择文件
//            intent.setType("*/*");//选择的文件 无类型限制
//            startActivityForResult(intent, OPEN_FILE_CODE);

//            File file = new File(cos_path);
//            String cosPath = "13522424667" + File.separator + file.getName();//对象在存储桶中的位置标识符，即称对象键
                        //获取当前时间
                        @SuppressLint("SimpleDateFormat")
                        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");// HH:mm:ss
                        Date date = new Date(System.currentTimeMillis());
                        Log.d("fill", simpleDateFormat.format(date));
                        Log.d("fill", ToolUtils.date2TimeStamp(simpleDateFormat.format(date), "yyyy年MM月dd日 HH:mm:ss"));
                        String cosPath = preferences.getString("username", "") + "/" + ToolUtils.getLocalPathFileName(cos_path); //对象在存储桶中的位置标识符，即称对象键
                        String srcPath = new File(context.getExternalCacheDir().getAbsolutePath(), cos_path).toString();//本地文件的绝对路径
                        File localFile = new File("C:/Users/Administrator/Desktop/budan/app/src/main/assets/agreement.html");//本地文件的相对路径
                        String uploadId = null; //若存在初始化分块上传的 UploadId，则赋值对应的 uploadId 值用于续传；否则，赋值 null
                        Log.d("fill对象在存储桶中的位置标识符即称对象键：", cosPath);
                        Log.d("fill本地文件的相对路径：", cos_path);
//            Log.d("fill", Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getAbsolutePath());
//            Log.d("fill", srcPath+ "" +localFile.toString() +Uri.fromFile(createImgFile()).toString());
                        PutObjectRequest putObjectRequest = new PutObjectRequest(getToken.getBucketName(), cosPath, cos_path);
                        putObjectRequest.setProgressListener(new CosXmlProgressListener() {
                            @Override
                            public void onProgress(long progress, long max) {
                                // todo Do something to update progress...
                            }
                        });
                        // 设置签名校验 Host，默认校验所有 Header
                        Set<String> headerKeys = new HashSet<>();
                        headerKeys.add("Host");
                        putObjectRequest.setSignParamsAndHeaders(null, headerKeys);
                        putObjectRequest.setNeedMD5(false);
                        // 使用同步方法上传
//            try {
//                PutObjectResult putObjectResult = cosXmlService.putObject(putObjectRequest);//没有用
//            } catch (CosXmlClientException e) {
//                e.printStackTrace();
//            } catch (CosXmlServiceException e) {
//                e.printStackTrace();
//            }
                        Log.d("fill", getToken.getBucketName());// hellobudansquare-1301790974
                        cosxmlTask = transferManager.upload(getToken.getBucketName(), cosPath, cos_path, uploadId);
                        cosxmlTask = transferManager.upload(putObjectRequest, uploadId);
//            cosxmlTask.setTransferStateListener(new TransferStateListener() {
//                @RequiresApi(api = Build.VERSION_CODES.O)
//                @Override
//                public void onStateChanged(final TransferState state) {
//                    ToolUtils.showToast(context, "刷新上传状态" + state.name());
//                    Log.d("fill---", state.name());//IN_PROGRESS
//                    if (state.name().equals("PAUSED")){
//                        Log.d("fill---", state.getDeclaringClass().toGenericString());
//                    }
//                }
//            });
                        cosxmlTask.setCosXmlProgressListener(new CosXmlProgressListener() {
                            @Override
                            public void onProgress(final long complete, final long target) {
                                //刷新上传进度
                            }
                        });
                        cosxmlTask.setCosXmlResultListener(new CosXmlResultListener() {
                            @Override
                            public void onSuccess(CosXmlRequest request, CosXmlResult result) {
                                Log.d("fill---", result.printResult());
                                COSXMLUploadTask.COSXMLUploadTaskResult cOSXMLUploadTaskResult = (COSXMLUploadTask.COSXMLUploadTaskResult) result;
                                cosxmlTask = null;
                                Log.d("fill---", cOSXMLUploadTaskResult.printResult());//200|OK
                                Log.d("fill---", cOSXMLUploadTaskResult.eTag);//52e7b8e3761e368945c52e1cf34f4f2e
                                Log.d("fill---", cOSXMLUploadTaskResult.accessUrl);//没用
                                Log.d("fill---", cOSXMLUploadTaskResult.httpMessage);//OK
                                if (type == 2){
                                    SharedPreferences preferences = context.getSharedPreferences("photo_path", Context.MODE_PRIVATE);
                                    SharedPreferences.Editor editor = preferences.edit();
                                    editor.putString("path", cosPath);//cos绝对路径
                                    editor.apply();
                                    finish();
                                } else {
                                    JSONObject object1 = new JSONObject();
                                    //直接用选择的文件URI去展示图片
                                    //如果所选文件不是图片文件，则展示文件图标
                                    try{
                                        object1.put("type", cos_bucket);
                                        object1.put("path", cosPath);//cos绝对路径
                                        object1.put("p_id", 0);
                                        object1.put("sort", 1);
                                    } catch (Exception e){
                                        e.printStackTrace();
                                    }
                                    postImgData(object1, access_token, context, cosPath, cOSXMLUploadTaskResult.accessUrl, type);//头像图片获取
                                }
                            }

                            @Override
                            public void onFail(CosXmlRequest request, CosXmlClientException exception, CosXmlServiceException serviceException) {
                                if (cosxmlTask.getTaskState() != TransferState.PAUSED) {
                                    cosxmlTask = null;
                                    //上传失败
                                }
                                exception.printStackTrace();
                                serviceException.printStackTrace();
                            }
                        });
                    } else {
                        ToolUtils.showToast(context, message);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                ToolUtils.showToast(context, "网络请求失败，请稍后重试~");
            }
        });
        request.setTag(this);
        VolleyUtil.getQueue(this).add(request);
    }

    /**
     * 网络请求
     * @param object
     */
    private void postImgData(JSONObject object, String access_token, Context context, String cosPath, String image, int type) {
        Log.d("fill_information", object.toString());
        JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, RequestConnect.fill_information_icon_Url + access_token, object, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {
                Log.d("fill_information", jsonObject.toString());
                try {
                    int code = jsonObject.optInt("code");
                    int status = jsonObject.optInt("status");
                    String message = jsonObject.getString("message");
                    if (code == 0) {
                        JSONObject info = jsonObject.getJSONObject("info");
                        String path = info.getString("path");//图片cos访问地址
                        if (type == 1){
                            Intent intent = new Intent(context, Publish_Activity.class);
                            intent.putExtra("access_token", access_token);
                            intent.putExtra("image_path", image);
                            intent.putExtra("path", cosPath);
                            context.startActivity(intent);
                        } else {
                            SharedPreferences preferences = context.getSharedPreferences("photo_path", Context.MODE_PRIVATE);
                            SharedPreferences.Editor editor = preferences.edit();
                            editor.putString("path", path);
                            editor.apply();
                        }
                        finish();
                    } else {
                        ToolUtils.showToast(context, message);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                ToolUtils.showToast(PhotoAlbum_Activity.this, "网络请求失败，请稍后重试~");
            }
        });
        request.setTag(this);
        VolleyUtil.getQueue(this).add(request);
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        cosxmlTask = null;
        SharedPreferences preferences = getSharedPreferences("photo_path", Context.MODE_PRIVATE);
        if (preferences.getString("path", "").equals("")){
            ToolUtils.showToast(PhotoAlbum_Activity.this, "path~");
        } else {
            PhotoAlbum_Activity.this.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    upload(currentUploadPath, bucket, access_token, PhotoAlbum_Activity.this, cos_type);
                }
            });
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (cosxmlTask != null && cosxmlTask.getTaskState() == TransferState.IN_PROGRESS) {
            cosxmlTask.pause();//恢复上传
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (cosxmlTask != null && cosxmlTask.getTaskState() == TransferState.PAUSED) {
            cosxmlTask.resume();//暂停上传
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (cosXmlService != null && cosxmlTask != null) {
            cosXmlService.release();
            cosxmlTask.cancel();//取消上传
        }
    }
}
